package com.example.smartagrisys.controller;

import com.example.smartagrisys.common.Result;
import com.example.smartagrisys.dto.LoginDTO;
import com.example.smartagrisys.dto.PasswordDTO;
import com.example.smartagrisys.dto.RegisterDTO;
import com.example.smartagrisys.dto.UserUpdateDTO;
import com.example.smartagrisys.entity.User;
import com.example.smartagrisys.service.UserService;
import com.example.smartagrisys.util.JwtUtil;
import com.example.smartagrisys.util.SecurityUtil;
import com.example.smartagrisys.vo.LoginVO;
import com.example.smartagrisys.vo.UserInfoVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

/**
 * 认证和用户控制器
 */
@Slf4j
@RestController
public class AuthController {

    @Autowired
    private UserService userService;

    @Autowired
    private JwtUtil jwtUtil;

    /**
     * 登录
     * @param loginDTO 登录信息
     * @return 登录结果
     */
    @PostMapping("/auth/login")
    public Result<LoginVO> login(@Valid @RequestBody LoginDTO loginDTO) {
        log.info("用户登录：{}", loginDTO.getUsername());
        
        // 登录验证
        User user = userService.login(loginDTO.getUsername(), loginDTO.getPassword());
        
        // 生成 token
        String token = jwtUtil.generateToken(user);
        
        // 构建返回数据
        LoginVO loginVO = new LoginVO();
        loginVO.setId(user.getId());
        loginVO.setUsername(user.getUsername());
        loginVO.setNickname(user.getNickname());
        loginVO.setRole(user.getRole());
        loginVO.setToken(token);
        
        return Result.success(loginVO, "登录成功");
    }

    /**
     * 注册
     * @param registerDTO 注册信息
     * @return 注册结果
     */
    @PostMapping("/auth/register")
    public Result<LoginVO> register(@Valid @RequestBody RegisterDTO registerDTO) {
        log.info("用户注册：{}", registerDTO.getUsername());
        
        // 注册用户
        User user = new User();
        BeanUtils.copyProperties(registerDTO, user);
        user = userService.register(user);
        
        // 生成 token
        String token = jwtUtil.generateToken(user);
        
        // 构建返回数据
        LoginVO loginVO = new LoginVO();
        loginVO.setId(user.getId());
        loginVO.setUsername(user.getUsername());
        loginVO.setNickname(user.getNickname());
        loginVO.setRole(user.getRole());
        loginVO.setToken(token);
        
        return Result.success(loginVO, "注册成功");
    }
    
    /**
     * 获取当前登录用户信息
     * @return 用户信息
     */
    @GetMapping("/user/info")
    public Result<UserInfoVO> getUserInfo() {
        // 获取当前登录用户
        User user = SecurityUtil.getCurrentUser();
        if (user == null) {
            return Result.error("用户未登录");
        }
        
        // 转换为VO对象
        UserInfoVO userInfoVO = new UserInfoVO();
        BeanUtils.copyProperties(user, userInfoVO);
        
        return Result.success(userInfoVO);
    }

    /**
     * 更新用户信息
     * @param userUpdateDTO 用户更新信息
     * @return 更新结果
     */
    @PutMapping("/user/update")
    public Result<UserInfoVO> updateUserInfo(@Valid @RequestBody UserUpdateDTO userUpdateDTO) {
        // 获取当前登录用户
        User currentUser = SecurityUtil.getCurrentUser();
        if (currentUser == null) {
            return Result.error("用户未登录");
        }
        
        log.info("更新用户信息：{}", currentUser.getUsername());
        
        // 更新用户信息
        User user = new User();
        user.setId(currentUser.getId());
        user.setNickname(userUpdateDTO.getNickname());
        user.setEmail(userUpdateDTO.getEmail());
        user.setPhone(userUpdateDTO.getPhone());
        
        boolean success = userService.updateById(user);
        if (!success) {
            return Result.error("更新失败");
        }
        
        // 获取更新后的用户信息
        user = userService.getById(currentUser.getId());
        
        // 转换为VO对象
        UserInfoVO userInfoVO = new UserInfoVO();
        BeanUtils.copyProperties(user, userInfoVO);
        
        return Result.success(userInfoVO, "更新成功");
    }

    /**
     * 修改密码
     * @param passwordDTO 密码信息
     * @return 修改结果
     */
    @PutMapping("/user/password")
    public Result<Void> changePassword(@Valid @RequestBody PasswordDTO passwordDTO) {
        // 获取当前登录用户
        User currentUser = SecurityUtil.getCurrentUser();
        if (currentUser == null) {
            return Result.error("用户未登录");
        }
        
        log.info("修改密码：{}", currentUser.getUsername());
        
        // 验证旧密码
        if (!userService.verifyPassword(currentUser.getId(), passwordDTO.getOldPassword())) {
            return Result.error("旧密码不正确");
        }
        
        // 修改密码
        boolean success = userService.changePassword(currentUser.getId(), passwordDTO.getNewPassword());
        if (!success) {
            return Result.error("修改失败");
        }
        
        return Result.success(null, "修改成功");
    }
} 